<?php

require_once 'Zend/Controller/Router/Route.php';
require_once 'Rest/Controller/Action.php';

class Rest_Route extends Zend_Controller_Router_Route
{

	protected $_method;

	/**
	 * Instantiates route based on passed Zend_Config structure
	 *
	 * @param Zend_Config $config Configuration object
	 */
	public static function getInstance(Zend_Config $config)
	{
		$reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array();
		$defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
		$method = ($config->method) ? $config->method : 'GET';
		return new self($config->route, $defs, $reqs, $method);
	}

	/**
	 * Prepares the route for mapping by splitting (exploding) it
	 * to a corresponding atomic parts. These parts are assigned
	 * a position which is later used for matching and preparing values.
	 * 
	 * The method may be specified which will factor into the mapping of this
	 * route. If clients use the POST method with a variable named "method"
	 * which is equal to PUT, DELETE, HEAD, or OPTION then that will override
	 * the HTTP method, allowing clients who can only use GET and POST (e.g. a
	 * web browser) to still access the APIs.
	 *
	 * @param string $route Map used to match with later submitted URL path
	 * @param array $defaults Defaults for map variables with keys as variable names
	 * @param array $reqs Regular expression requirements for variables (keys as variable names)
	 * @param string $method string indicating the HTTP method for RESTful APIs
	 */
	public function __construct($route, $defaults = array(), $reqs = array(), $method = 'GET')
	{
		parent::__construct($route, $defaults, $reqs);
		$this->_method = $method;
	}

	/**
	 * Matches a user submitted path with parts defined by a map. Assigns and
	 * returns an array of variables on a successful match.
	 *
	 * @param string $path Path used to match against this routing map
	 * @return array|false An array of assigned values or a false on a mismatch
	 */
	public function match($path)
	{
		Rest_Controller_Action::startRest();
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$method = $request->getMethod();
		
		if ($method != $this->_method)
			return false;
		else
			return parent::match($path);
	}
}
